<template>
  <div id="pictureManagePage">
    <a-space>
      <a-button type="primary" href="/addPicture">+ 创建图片</a-button>
      <a-button type="primary" href="/addPicture/batch" ghost>+ 批量创建图片</a-button>
    </a-space>

    <!-- 搜索条件 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="关键词" name="searchText">
        <a-input
          v-model:value="searchParams.searchText"
          placeholder="从名称和简介中搜索"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="类型" name="category">
        <a-input v-model:value="searchParams.category" placeholder="请输入类型" allow-clear />
      </a-form-item>
      <a-form-item label="标签" name="tags">
        <a-select
          v-model:value="searchParams.tags"
          placeholder="请选择标签"
          allow-clear
          show-search
          mode="multiple"
          :options="tagOptions"
          style="min-width: 180px"
        />
      </a-form-item>
      <a-form-item label="审核状态" name="reviewStatus">
        <a-select
          v-model:value="searchParams.reviewStatus"
          :options="PIC_REVIEW_STATUS_OPTIONS"
          placeholder="请输入审核状态"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
        <a-button style="margin-left: 10px" type="default" @click="resetSearch">重置</a-button>
      </a-form-item>
    </a-form>

    <div style="margin-bottom: 16px; margin-top: 10px">
      <a-button type="primary" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
        批量删除 (已选 {{ selectedIds.length }} 项)
      </a-button>
    </div>

    <a-table
      row-key="id"
      :row-selection="rowSelection"
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
      bordered
      :scroll="{ x: 'max-content' }"
      size="middle"
      style="margin-top: 5px"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'url'">
          <!--          <a-image :src="record.url" :width="120" />-->
          <a-image
            :src="record.url"
            :width="120"
            :height="120"
            class="picture-preview"
            :preview="{
              src: record.url,
              mask: '预览',
            }"
          />
        </template>
        <template v-if="column.dataIndex === 'name'">
          <a-tooltip :title="record.name">
            <span class="text-ellipsis" :title="record.name">{{ record.name }}</span>
          </a-tooltip>
        </template>
        <!-- 标签 -->
        <template v-else-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!-- 图片信息 -->
        <template v-if="column.dataIndex === 'picInfo'">
          <div>格式：{{ record.picFormat }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}KB</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>宽高比：{{ record.picScale }}</div>
        </template>
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!-- 审核信息 -->
        <template v-if="column.dataIndex === 'reviewMessage'">
          <div>审核状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审核信息：{{ record.reviewMessage }}</div>
          <div>审核人：{{ record.reviewerId }}</div>
          <div v-if="record.reviewTime">
            审核时间：{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}
          </div>
        </template>

        <template v-else-if="column.key === 'action' && record.userRole !== 'admin'">
          <a-space wrap :size="8" class="action-buttons">
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS"
              type="default"
              size="small"
              :icon="h(CheckCircleOutlined)"
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.PASS)"
            >
              通过
            </a-button>
            <a-button
              v-if="record.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT"
              size="small"
              danger
              :icon="h(CloseCircleOutlined)"
              @click="handleReview(record, PIC_REVIEW_STATUS_ENUM.REJECT)"
            >
              拒绝
            </a-button>
            <a-button
              type="primary"
              :icon="h(EditOutlined)"
              size="small"
              @click="handleEdit(record.id)"
            >
              编辑
            </a-button>
            <a-button
              danger
              :icon="h(DeleteOutlined)"
              size="small"
              @click="showDeleteConfirm(record.id)"
              >删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 确认删除对话框 -->
    <a-modal
      v-model:visible="confirmModalVisible"
      title="确认删除"
      @ok="handleDeleteOk"
      @cancel="handleDeleteCancel"
    >
      <p>您确定要删除该图片吗？</p>
    </a-modal>

    <!-- 审核确认对话框 -->
    <a-modal
      v-model:visible="reviewModalVisible"
      :title="reviewModalTitle"
      @ok="handleReviewOk"
      @cancel="handleReviewCancel"
    >
      <a-form :model="reviewForm" layout="vertical">
        <a-form-item label="审核意见" name="reviewMessage">
          <a-textarea
            v-model:value="reviewForm.reviewMessage"
            :placeholder="
              reviewForm.reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS
                ? '请输入通过原因（选填）'
                : '请输入拒绝原因（必填）'
            "
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref, h } from 'vue'
import {
  batchDeletePictureUsingPost,
  deletePictureUsingPost,
  doPictureReviewUsingPost,
  listPictureByPageUsingPost,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { message } from 'ant-design-vue/es/components'
import dayjs from 'dayjs'
import type { Key } from 'ant-design-vue/lib/vc-table/interface'
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  DeleteOutlined,
  EditOutlined,
} from '@ant-design/icons-vue/lib/icons'
import { useRouter } from 'vue-router'
import {
  PIC_REVIEW_STATUS_ENUM,
  PIC_REVIEW_STATUS_MAP,
  PIC_REVIEW_STATUS_OPTIONS,
} from '@/constants/picture.ts'

const dataList = ref([])
const total = ref(0)
const confirmModalVisible = ref(false)
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const pictureId = ref(0)
const selectedIds = ref<number[]>([])
const router = useRouter()
const reviewModalVisible = ref(false)
const reviewModalTitle = ref('')
const currentRecord = ref<API.Picture | null>(null)
// 审核表单
const reviewForm = reactive({
  reviewStatus: 0,
  reviewMessage: '',
})

//搜索条件
const searchParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'createTime',
  sortOrder: 'descend',
})

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center',
  },
  {
    title: '图片',
    dataIndex: 'url',
    align: 'center',
  },
  {
    title: '名称',
    dataIndex: 'name',
    align: 'center',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
    ellipsis: true,
    align: 'center',
  },
  {
    title: '类型',
    dataIndex: 'category',
    align: 'center',
  },
  {
    title: '标签',
    dataIndex: 'tags',
    align: 'center',
  },
  {
    title: '图片信息',
    dataIndex: 'picInfo',
    align: 'center',
  },
  {
    title: '用户 id',
    dataIndex: 'userId',
    align: 'center',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
    align: 'center',
  },
  {
    title: '审核信息',
    dataIndex: 'reviewMessage',
    align: 'center',
  },
  {
    title: '操作',
    key: 'action',
    align: 'center',
  },
]

const rowSelection = {
  onChange: (selectedRowKeys: Key[], selectedRows: DataType[]) => {
    selectedIds.value = selectedRows.map((row) => row.id)
  },
}

const showDeleteConfirm = (id: number) => {
  pictureId.value = id
  confirmModalVisible.value = true
}
const handleEdit = (id: number) => {
  router.push('/addPicture?id=' + id)
}

const handleDeleteOk = () => {
  if (pictureId.value) {
    doDelete(pictureId.value)
  }
  confirmModalVisible.value = false
}

const handleDeleteCancel = () => {
  confirmModalVisible.value = false
  fetchData()
}

const doDelete = async (id: number) => {
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    await fetchData()
  } else {
    message.error('删除失败')
  }
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    message.error('请先选择要删除的图片')
    return
  }
  const res = await batchDeletePictureUsingPost({ ids: selectedIds.value })
  if (res.data.code === 0) {
    message.success('批量删除成功')
    // 刷新数据
    await fetchData()
  } else {
    message.error('批量删除失败')
  }
}

const handleReview = (record: API.Picture, reviewStatus: number) => {
  currentRecord.value = record
  reviewForm.reviewStatus = reviewStatus
  reviewForm.reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '管理员操作通过' : ''
  reviewModalTitle.value =
    reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '确认通过审核' : '确认拒绝审核'
  reviewModalVisible.value = true
}

const handleReviewOk = async () => {
  // 如果是拒绝状态，必须填写拒绝原因
  if (
    reviewForm.reviewStatus === PIC_REVIEW_STATUS_ENUM.REJECT &&
    !reviewForm.reviewMessage.trim()
  ) {
    message.error('请填写拒绝原因')
    return
  }

  if (!currentRecord.value) {
    message.error('操作失败，数据异常')
    return
  }

  const res = await doPictureReviewUsingPost({
    id: currentRecord.value.id,
    reviewStatus: reviewForm.reviewStatus,
    reviewMessage: reviewForm.reviewMessage,
  })

  if (res.data.code === 0) {
    message.success('审核操作成功')
    reviewModalVisible.value = false
    // 重新获取列表
    fetchData()
  } else {
    message.error('审核操作失败，' + res.data.message)
  }
}

const handleReviewCancel = () => {
  reviewModalVisible.value = false
}

//请求数据
const fetchData = async () => {
  const res = await listPictureByPageUsingPost({ ...searchParams })
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败:' + res.data.message)
  }
}

// 获取数据
const doSearch = () => {
  // 重置搜索条件
  searchParams.current = 1
  fetchData()
}

// 表格变化处理
const doTableChange = (page: any) => {
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
}

// 重置搜索条件
const resetSearch = () => {
  searchParams.searchText = ''
  searchParams.category = ''
  searchParams.tags = undefined
  searchParams.current = 1
  fetchData()
}

//分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current ?? 1,
    pageSize: searchParams.pageSize ?? 10,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    //转换成下拉框的格式
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

onMounted(() => {
  fetchData()
  getTagCategoryOptions()
})
</script>

<style scoped>
.text-ellipsis {
  display: inline-block;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-buttons .ant-space-item {
  margin-bottom: 4px !important;
}

/* 图片预览样式 */

.picture-preview {
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  object-fit: cover;
  transition: all 0.3s;
}

.picture-preview:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 确保图片容器有统一的尺寸 */

:deep(.ant-image) {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 120px;
  height: 90px;
  background-color: #f5f5f5;
}
</style>
